package xdu.lz.stage4_atomic.chapter2_caslock;

public class CASLockTest {

    private static final CASLock lock = new CASLock();

    public static void main(String[] args) throws InterruptedException {

        //线程2抢锁失败
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                doSomething(100);
            },"t"+i).start();
        }

        Thread.sleep(5000);

        // 1s
        new Thread(()->{
            doSomething(1000);
        },"t10").start();

        //保证t10启动
        Thread.sleep(10);


        try {
            //如果时间大于1100，会成功获取锁，否则会抛出超时异常
            lock.tryLock(2000);
        } catch (TimeOutException e) {
            e.printStackTrace();
//            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
            System.out.println("main release the lock");
        }
    }

    private static void doSomething(long mills) {
        try {
            lock.tryLock();
            System.out.println(Thread.currentThread().getName()+ " get the chapter2_caslock");
            Thread.sleep(mills);
        } catch (GetLockException e) {
            e.printStackTrace();
        } catch (InterruptedException e){

        }finally {
            System.out.println(Thread.currentThread().getName()+ " release the chapter2_caslock");
            lock.unlock();
        }
    }

}
